<template>
  <div id="FileResource">
    <a-form layout="inline" style="margin-bottom: 8px">
      <a-form-item label="课程信息" class="searchItem">
        <a-select v-model="curriculumId" style="width: 180px">
          <a-select-option
            v-for="item in curriculumIdList"
            :key="item.id"
            :value="item.id"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item label="关键字" class="searchItem">
        <a-input v-model="keyword" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="">
        <a-button type="primary" @click="getData"> 查询 </a-button>
      </a-form-item>
    </a-form>
    <a-button type="primary" @click="downLoadClick" class="downLoad"
      >下载</a-button
    >
    <div v-if="!curriculumId" style="height: 20px">
      <a-button
        type="primary"
        style="margin-right: 8px; float: right"
        @click="messageShow"
        >导入</a-button
      >
    </div>
    <div v-else style="display: flex; justify-content: flex-end">
      <a-upload
        ref="uploadRef"
        class="upload"
        name="file"
        :data="getUploadParams"
        :before-upload="handleBeforeUpload"
        :multiple="true"
        :show-upload-list="false"
        :custom-request="customUploadRequest"
      >
        <a-button type="primary" style="margin-left: 8px">导入</a-button>
      </a-upload>
    </div>
    <a-table
      :scroll="{ y: 450 }"
      :columns="columns"
      style="margin-top: 30px"
      :data-source="tableData"
      :pagination="tablePagination"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :rowKey="(record, index) => record.id"
      @change="handleTableChange"
    >
      <template slot="name" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.name">
          <template slot="title">
            <span>{{ record.name }}</span>
          </template>
          <span style="cursor: default">{{ record.name }}</span>
        </a-tooltip>
        <span v-else-if="!record.name">—</span>
      </template>
      <template slot="tapdProjectId" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.tapdProjectId">
          <template slot="title">
            <p>{{ record.tapdProjectId }}</p>
          </template>
          <span style="cursor: default">{{ record.tapdProjectId }}</span>
        </a-tooltip>
        <span v-else-if="!record.tapdProjectId">—</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <!-- <a-dropdown-button v-if="record.operation">
          操作
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="downLoad2(record)"> 预览 </a-menu-item>
            <a-menu-item key="2" @click="downLoad(record)"> 下载 </a-menu-item>
            <a-menu-item key="3" @click="assignClick(record)">
              分配权限
            </a-menu-item>
            <a-menu-item key="4" @click="deleteClick(record)">
              删除
            </a-menu-item>
          </a-menu>
        </a-dropdown-button> -->
        <div v-if="record.operation">
          <a-button type="primary" @click="downLoad2(record)">预览</a-button>
          <!-- <a-button
            type="primary"
            style="margin-left: 10px"
            @click="downLoad(record)"
            >下载</a-button
          > -->
          <a-button
            type="primary"
            style="margin-left: 10px"
            @click="assignClick(record)"
            >分配权限</a-button
          >
          <a-button
            type="danger"
            style="margin-left: 10px"
            @click="deleteClick(record)"
            >删除</a-button
          >
        </div>
      </template>
    </a-table>
    <a-modal v-model="visible" :maskClosable="false" title="分配权限">
      <a-form-model
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
        ref="formRef"
        :model="form"
        :rules="rules"
      >
        <a-form-model-item label="教员选择" prop="userIds">
          <a-select
            v-model="form.userIds"
            style="width: 236px"
            mode="multiple"
            :maxTagCount="1"
          >
            <a-select-option
              v-for="item in userIdList"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button key="back" class="modalCancel" @click="handleCancel"
          >取消</a-button
        >
        <a-button key="submit" @click="primaryClick" type="primary">
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      FileId: null, //选中的文件id,用于分配权限
      form: {
        userIds: [],
      },
      userIdList: [],
      rules: {
        userIds: [{ required: true, message: "请选择教员", trigger: "blur" }],
      },
      curriculumId: null,
      curriculumIdList: [],
      coursePlanId: null, //课程所选中的值
      keyword: null, //关键字
      selectedRowKeys: [],
      columns: [
        //主页table列的配置
        {
          title: "课程名称",
          dataIndex: "curriculumName",
          customRender: (text, record) => {
            return record.curriculumName ? record.curriculumName : "—";
          },
        },
        {
          title: "文件名称",
          dataIndex: "fileName",
          customRender: (text, record) => {
            return record.fileName ? record.fileName : "—";
          },
        },
        {
          title: "文件类型",
          dataIndex: "fileType",
          customRender: (text, record) => {
            return record.fileType ? record.fileType : "—";
          },
        },
        {
          title: "文件地址",
          dataIndex: "filePath",
          customRender: (text, record) => {
            return record.filePath ? record.filePath : "—";
          },
        },
        {
          title: "操作",
          width: 300,
          align: "center",
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      tableData: [
        //主页表格的数据
      ],
      tablePagination: {
        //主页表格的分页器
        total: 0,
        current: 1,
        pageSize: 10,
        showQuickJumper: true, //是否可以快速跳转至某页
        showSizeChanger: true, //是否可以改变 pageSize
      },
    };
  },
  created() {
    this.getData(); //获取列表数据
    this.getCurriculumIdList(); //获取课程信息的下拉
    this.getUserIdList(); //获取教员的下拉选项
  },
  methods: {
    downLoadClick() {
      if (this.selectedRowKeys.length != 1) {
        this.$message.warning("请选择一条数据进行下载,仅支持一条数据的下载");
        return false;
      }
      let obj = this.tableData.find(
        (item) => item.id == this.selectedRowKeys[0]
      );
      this.downLoad({ id: this.selectedRowKeys[0], fileName: obj.fileName });
    },
    handleCancel() {
      this.form.userIds = [];
      this.$refs.formRef.resetFields();
      this.visible = false;
    },
    primaryClick() {
      let data = {
        id: this.FileId,
        userIds: this.form.userIds,
      };
      this.$axios.post("/curriculum/resource/allot", data).then((res) => {
        if (res.code == 200) {
          this.$message.success("分配权限成功");
          this.handleCancel();
          this.getData();
        }
      });
    },
    getUserIdList() {
      this.$axios.get("/educator/options").then((res) => {
        if (res.code == 200) {
          this.userIdList = res.data;
        }
      });
    },
    assignClick(row) {
      this.FileId = row.id;
      this.visible = true;
    },
    customUploadRequest({ file, onSuccess, onError }) {
      const formData = new FormData();
      // 添加文件到 FormData
      formData.append("file", file);
      // 如果需要其他参数，可以在这里添加
      // formData.append('additionalParam', 'value');
      let params = {
        id: this.curriculumId,
      };
      this.$axios
        .post("/curriculum/resource/upload/file", formData, { params })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("上传成功");
            this.curriculumId = null;
            this.getData();
          }
        });
    },
    messageShow() {
      if (!this.curriculumId) {
        this.$message.warning("请选择课程信息");
      }
    },
    getCurriculumIdList() {
      //获取课程基础信息的下拉
      this.$axios.get("/curriculum/options").then((res) => {
        this.curriculumIdList = res.data;
      });
    },
    handleTableChange(pagination, filters, sorter) {
      this.tablePagination.current = pagination.current;
      this.tablePagination.pageSize = pagination.pageSize;
      this.getData();
    },
    downLoad(row) {
      this.$axios
        .get("/curriculum/resource/download", {
          params: {
            id: row.id,
          },
          responseType: "blob", // 关键：指定返回数据类型为 blob
        })
        .then((res) => {
          const downloadUrl = window.URL.createObjectURL(res);
          const link = document.createElement("a"); // 创建隐藏的下载链接
          link.href = downloadUrl;
          const filename = row.fileName; //文件名可以从响应头或请求参数中获取
          link.download = filename;
          link.click();
          link.remove();
        });
    },
    downLoad2(row) {
      this.$axios
        .get("/curriculum/resource/download", {
          params: {
            id: row.id,
            preview: 1,
          },
          responseType: "blob", // 关键：指定返回数据类型为 blob
        })
        .then((res) => {
          const downloadUrl = window.URL.createObjectURL(res);
          const link = document.createElement("a"); // 创建隐藏的下载链接
          link.href = downloadUrl;
          const filename = row.fileName; //文件名可以从响应头或请求参数中获取
          link.download = filename;
          link.click();
          link.remove();
        });
    },
    deleteClick(row) {
      //点击删除
      let data = {
        id: row.id,
      };
      let that = this;
      this.$confirm({
        title: "确认删除?",
        content: "您确定要删除此项吗?",
        onOk() {
          that.$axios
            .delete("/curriculum/resource/delete", { data })
            .then((res) => {
              if (res.code == 200) {
                that.$message.success("删除成功");
                that.getData();
              }
            });
        },
        onCancel() {
          console.log("取消删除");
        },
      });
    },
    getUploadParams(file) {
      // 动态返回参数，根据文件的类型、大小等来决定要上传的参数
      return {
        name: file.name, //文件名
        desc: null, //文件描述
        type: file.type, // 文件类型
        coursePlanId: this.coursePlanId, //课程计划id
      };
    },
    handleBeforeUpload(file) {
      //文件上传的上传文件弹出框弹出之前的回调
      return true;
    },
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    async getData() {
      let { data } = await this.$axios.get("/curriculum/resource/page/list", {
        //该接口是查询除了指定类型type的其他所有数据,这里是查除了model类型的所有数据
        params: {
          page: this.tablePagination.current,
          size: this.tablePagination.pageSize,
          curriculumId: this.curriculumId, //课程名称
          keyword: this.keyword, //关键字(也是题目内容)
        },
      });
      this.tableData = data.records;
      this.tablePagination.total = data.total;
    },
  },
};
</script>

<style lang="scss">
#FileResource {
  position: relative;
  .upload {
    position: relative;
    .ant-upload-list {
      position: absolute;
      right: 0;
      .ant-upload-list-item {
        width: 200px;
      }
    }
  }
  .downLoad {
    position: absolute;
    right: 90px;
  }
}
</style>